<template>
  <div class="bad-deeds-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-wrapper">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a @click="goBack">因果业力系统</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>恶行记录管理</a-breadcrumb-item>
      </a-breadcrumb>
      <a-button type="text" @click="goBack" class="back-button">
        <LeftOutlined />
        返回上级
      </a-button>
    </div>

    <!-- 页面标题 -->
    <div class="ancient-title">恶行记录管理</div>

    <!-- 统计概览 -->
    <a-row :gutter="[24, 24]" class="stats-row">
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="恶行总数" :value="badDeedsData.length" :value-style="{ color: '#f5222d', fontSize: '24px' }" suffix="条" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="罪孽总分" :value="totalBadScore" :value-style="{ color: '#fa541c', fontSize: '24px' }" suffix="分" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="受害者总数" :value="totalVictims" :value-style="{ color: '#722ed1', fontSize: '24px' }" suffix="人" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="本月新增" :value="thisMonthCount" :value-style="{ color: '#fa8c16', fontSize: '24px' }" suffix="条" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 严重等级警报 -->
    <a-row :gutter="[24, 24]" class="alert-row" v-if="severeCrimes.length > 0">
      <a-col :span="24">
        <a-alert :message="`发现 ${severeCrimes.length} 起严重罪行，需要重点关注`" type="error" show-icon banner>
          <template #description>
            <div class="severe-crimes-list">
              <a-tag v-for="crime in severeCrimes.slice(0, 3)" :key="crime.id" color="red" style="margin: 2px"> {{ crime.personName }} - {{ karmaRules.badDeeds[crime.action]?.name }} </a-tag>
              <span v-if="severeCrimes.length > 3">等...</span>
            </div>
          </template>
        </a-alert>
      </a-col>
    </a-row>

    <!-- 分类统计图表 -->
    <a-row :gutter="[24, 24]" class="charts-row">
      <a-col :xs="24" :lg="12">
        <a-card title="恶行类型分布" :bordered="false" class="chart-card">
          <div ref="categoryChart" style="height: 300px"></div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="12">
        <a-card title="严重程度分级" :bordered="false" class="chart-card">
          <div ref="severityChart" style="height: 300px"></div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 操作栏 -->
    <a-card :bordered="false" class="action-card">
      <a-row :gutter="[16, 16]" align="middle">
        <a-col :xs="24" :sm="7">
          <a-input-search v-model:value="searchQuery" placeholder="搜索人员姓名或描述" @search="handleSearch" />
        </a-col>
        <a-col :xs="24" :sm="5">
          <a-select v-model:value="categoryFilter" placeholder="恶行类型筛选" @change="handleFilterChange">
            <a-select-option value="all">全部类型</a-select-option>
            <a-select-option v-for="category in badDeedCategories" :key="category" :value="category">
              {{ category }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="5">
          <a-select v-model:value="severityFilter" placeholder="严重程度筛选" @change="handleFilterChange">
            <a-select-option value="all">全部等级</a-select-option>
            <a-select-option value="轻微">轻微</a-select-option>
            <a-select-option value="中等">中等</a-select-option>
            <a-select-option value="重大">重大</a-select-option>
            <a-select-option value="极重">极重</a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="4">
          <a-button type="primary" danger @click="showAddModal = true">
            <PlusOutlined />
            记录恶行
          </a-button>
        </a-col>
        <a-col :xs="24" :sm="3">
          <a-button @click="scrollToStatistics"> 查看统计 </a-button>
        </a-col>
      </a-row>
    </a-card>

    <!-- 恶行记录列表 -->
    <a-card title="恶行记录列表" :bordered="false" class="records-card">
      <a-table :columns="columns" :data-source="filteredBadDeeds" :loading="loading" row-key="id" :pagination="{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-tag :color="getActionColor(record.karmaCategory)">
              {{ karmaRules.badDeeds[record.action]?.name }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'category'">
            <a-tag color="red">{{ record.karmaCategory }}</a-tag>
          </template>

          <template v-else-if="column.key === 'severity'">
            <a-tag :color="getSeverityColor(karmaRules.badDeeds[record.action]?.level)">
              {{ karmaRules.badDeeds[record.action]?.level }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'score'">
            <span class="score-negative">{{ record.score }}</span>
          </template>

          <template v-else-if="column.key === 'victims'">
            <a-tooltip>
              <template #title>
                <div v-for="victim in record.victims" :key="victim">
                  {{ victim }}
                </div>
              </template>
              <a-tag color="orange">{{ record.victims?.length || 0 }}人</a-tag>
            </a-tooltip>
          </template>

          <template v-else-if="column.key === 'verified'">
            <a-tag :color="record.verified ? 'green' : 'orange'">
              {{ record.verified ? '已验证' : '待验证' }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="viewRecord(record)"> 查看详情 </a-button>
              <a-button type="link" size="small" @click="editRecord(record)"> 编辑 </a-button>
              <a-button type="link" size="small" @click="trackConsequences(record)"> 后果追踪 </a-button>
              <a-button type="link" size="small" danger @click="deleteRecord(record)"> 删除 </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详细统计区域 -->
    <div ref="statisticsSection" class="statistics-section">
      <div class="section-title">恶行详细统计分析</div>

      <!-- 类型统计 -->
      <a-card title="恶行类型统计" :bordered="false" class="statistics-card">
        <a-table :columns="categoryStatsColumns" :data-source="categoryStatistics" :pagination="false" size="small" row-key="category" />
      </a-card>

      <!-- 严重程度分析 -->
      <a-card title="严重程度分析" :bordered="false" class="statistics-card">
        <a-table :columns="severityStatsColumns" :data-source="severityStatistics" :pagination="false" size="small" row-key="level" />
      </a-card>

      <!-- 个人犯罪记录 -->
      <a-card title="个人犯罪记录排行" :bordered="false" class="statistics-card">
        <a-table :columns="personStatsColumns" :data-source="personStatistics" :pagination="{ pageSize: 10, showQuickJumper: true }" size="small" row-key="personName" />
      </a-card>
    </div>

    <!-- 添加/编辑恶行记录弹窗 -->
    <a-modal v-model:open="showAddModal" :title="editingRecord ? '编辑恶行记录' : '记录恶行'" width="800px" @ok="handleSaveRecord" @cancel="handleCancelEdit">
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="人员姓名" name="personName">
              <a-input v-model:value="formData.personName" placeholder="请输入人员姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="恶行类型" name="action">
              <a-select v-model:value="formData.action" placeholder="请选择恶行类型">
                <a-select-opt-group v-for="(actions, category) in badDeedsByCategory" :key="category" :label="category">
                  <a-select-option v-for="(rule, key) in actions" :key="key" :value="key"> {{ rule.name }} ({{ rule.score }}分) - {{ rule.level }} </a-select-option>
                </a-select-opt-group>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="恶行描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请详细描述该恶行" :rows="3" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="发生日期" name="date">
              <a-date-picker v-model:value="formData.date" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="发生时间" name="time">
              <a-time-picker v-model:value="formData.time" style="width: 100%" format="HH:mm" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="发生地点" name="location">
          <a-input v-model:value="formData.location" placeholder="请输入详细地点" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="见证人" name="witnesses">
              <a-select v-model:value="formData.witnesses" mode="tags" placeholder="请输入见证人姓名" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="受害者" name="victims">
              <a-select v-model:value="formData.victims" mode="tags" placeholder="请输入受害者信息" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="恶行后果" name="consequences">
          <a-textarea v-model:value="formData.consequences" placeholder="请描述这个恶行造成的后果和损失" :rows="2" />
        </a-form-item>

        <a-form-item label="证据材料" name="evidence">
          <a-select v-model:value="formData.evidence" mode="tags" placeholder="请输入证据材料（如：监控录像、报警记录、医院证明等）" style="width: 100%" />
        </a-form-item>

        <a-form-item label="处理状态" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio value="pending">待处理</a-radio>
            <a-radio value="investigating">调查中</a-radio>
            <a-radio value="processed">已处理</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 后果追踪弹窗 -->
    <a-modal v-model:open="showConsequenceModal" title="恶行后果追踪" width="700px" @ok="saveConsequenceTracking">
      <div v-if="currentRecord">
        <a-descriptions title="恶行基本信息" :column="2" size="small">
          <a-descriptions-item label="人员">{{ currentRecord.personName }}</a-descriptions-item>
          <a-descriptions-item label="恶行">{{ karmaRules.badDeeds[currentRecord.action]?.name }}</a-descriptions-item>
          <a-descriptions-item label="时间">{{ currentRecord.date }}</a-descriptions-item>
          <a-descriptions-item label="地点">{{ currentRecord.location }}</a-descriptions-item>
          <a-descriptions-item label="严重程度">{{ karmaRules.badDeeds[currentRecord.action]?.level }}</a-descriptions-item>
          <a-descriptions-item label="罪孽分数">{{ currentRecord.score }}分</a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-form layout="vertical">
          <a-form-item label="直接后果">
            <a-textarea v-model:value="consequenceTracking.direct" placeholder="描述直接造成的后果和损失" :rows="2" />
          </a-form-item>

          <a-form-item label="间接影响">
            <a-textarea v-model:value="consequenceTracking.indirect" placeholder="描述间接产生的影响" :rows="2" />
          </a-form-item>

          <a-form-item label="经济损失">
            <a-input-number v-model:value="consequenceTracking.economicLoss" placeholder="经济损失金额（元）" style="width: 100%" :min="0" />
          </a-form-item>

          <a-form-item label="精神损害评估 (1-10分)">
            <a-slider v-model:value="consequenceTracking.mentalDamage" :min="1" :max="10" :marks="{ 1: '轻微', 5: '中等', 10: '严重' }" />
          </a-form-item>

          <a-form-item label="社会影响评估 (1-10分)">
            <a-slider v-model:value="consequenceTracking.socialImpact" :min="1" :max="10" :marks="{ 1: '轻微', 5: '中等', 10: '严重' }" />
          </a-form-item>

          <a-form-item label="法律后果">
            <a-select v-model:value="consequenceTracking.legalConsequence" placeholder="选择法律后果">
              <a-select-option value="none">无</a-select-option>
              <a-select-option value="warning">警告</a-select-option>
              <a-select-option value="fine">罚款</a-select-option>
              <a-select-option value="detention">拘留</a-select-option>
              <a-select-option value="imprisonment">监禁</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="后续处理计划">
            <a-textarea v-model:value="consequenceTracking.followUp" placeholder="描述后续的处理和补救措施" :rows="2" />
          </a-form-item>
        </a-form>

        <a-alert :message="`综合严重度评分: ${consequenceTracking.totalSeverity}分`" :type="getSeverityLevel(consequenceTracking.totalSeverity).type" :description="getSeverityLevel(consequenceTracking.totalSeverity).description" show-icon />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, LeftOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useKarmaStore } from '@/stores'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

// 状态管理
const karmaStore = useKarmaStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showAddModal = ref(false)
const showConsequenceModal = ref(false)
const editingRecord = ref(null)
const currentRecord = ref(null)
const formRef = ref()
const searchQuery = ref('')
const categoryFilter = ref('all')
const severityFilter = ref('all')
const categoryChart = ref()
const severityChart = ref()
const statisticsSection = ref()

// 表单数据
const formData = reactive({
  personName: '',
  action: '',
  description: '',
  date: null,
  time: null,
  location: '',
  witnesses: [],
  victims: [],
  consequences: '',
  evidence: [],
  status: 'pending'
})

// 后果追踪数据
const consequenceTracking = reactive({
  direct: '',
  indirect: '',
  economicLoss: 0,
  mentalDamage: 5,
  socialImpact: 5,
  legalConsequence: 'none',
  followUp: '',
  totalSeverity: computed(() => {
    const economicScore = Math.min(10, consequenceTracking.economicLoss / 10000) // 每万元1分
    return (((consequenceTracking.mentalDamage + consequenceTracking.socialImpact + economicScore) / 3) * 10).toFixed(1)
  })
})

// 表单验证规则
const formRules = {
  personName: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
  action: [{ required: true, message: '请选择恶行类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入恶行描述', trigger: 'blur' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }]
}

// 计算属性
const { karmaRecords, karmaRules } = karmaStore

// 获取恶行数据
const badDeedsData = computed(() => karmaRecords.filter((record) => record.score < 0))

// 过滤后的恶行数据
const filteredBadDeeds = computed(() => {
  let result = badDeedsData.value

  if (searchQuery.value) {
    result = result.filter((record) => record.personName.includes(searchQuery.value) || record.description.includes(searchQuery.value))
  }

  if (categoryFilter.value !== 'all') {
    result = result.filter((record) => record.karmaCategory === categoryFilter.value)
  }

  if (severityFilter.value !== 'all') {
    result = result.filter((record) => {
      const rule = karmaRules.badDeeds[record.action]
      return rule?.level === severityFilter.value
    })
  }

  return result
})

// 恶行类型分类
const badDeedCategories = computed(() => {
  const categories = new Set()
  Object.values(karmaRules.badDeeds).forEach((rule) => {
    categories.add(rule.category)
  })
  return Array.from(categories)
})

// 按类别分组的恶行
const badDeedsByCategory = computed(() => {
  const grouped = {}
  Object.entries(karmaRules.badDeeds).forEach(([key, rule]) => {
    if (!grouped[rule.category]) {
      grouped[rule.category] = {}
    }
    grouped[rule.category][key] = rule
  })
  return grouped
})

// 严重犯罪列表
const severeCrimes = computed(() =>
  badDeedsData.value.filter((record) => {
    const rule = karmaRules.badDeeds[record.action]
    return rule?.level === '极重' || rule?.level === '重大'
  })
)

// 统计数据
const totalBadScore = computed(() => Math.abs(badDeedsData.value.reduce((sum, record) => sum + record.score, 0)))

const totalVictims = computed(() => {
  const victims = new Set()
  badDeedsData.value.forEach((record) => {
    record.victims?.forEach((victim) => victims.add(victim))
  })
  return victims.size
})

const thisMonthCount = computed(() => {
  const thisMonth = dayjs().format('YYYY-MM')
  return badDeedsData.value.filter((record) => record.date.startsWith(thisMonth)).length
})

// 类型统计
const categoryStatistics = computed(() => {
  const stats = {}
  badDeedsData.value.forEach((record) => {
    const category = record.karmaCategory
    if (!stats[category]) {
      stats[category] = {
        category,
        count: 0,
        totalScore: 0,
        avgScore: 0,
        victims: new Set()
      }
    }
    stats[category].count++
    stats[category].totalScore += Math.abs(record.score)
    record.victims?.forEach((v) => stats[category].victims.add(v))
  })

  return Object.values(stats).map((stat) => ({
    ...stat,
    avgScore: (stat.totalScore / stat.count).toFixed(1),
    victimsCount: stat.victims.size,
    victims: undefined
  }))
})

// 严重程度统计
const severityStatistics = computed(() => {
  const stats = {}
  badDeedsData.value.forEach((record) => {
    const rule = karmaRules.badDeeds[record.action]
    const level = rule?.level || '未知'
    if (!stats[level]) {
      stats[level] = {
        level,
        count: 0,
        totalScore: 0,
        avgScore: 0
      }
    }
    stats[level].count++
    stats[level].totalScore += Math.abs(record.score)
  })

  return Object.values(stats).map((stat) => ({
    ...stat,
    avgScore: (stat.totalScore / stat.count).toFixed(1)
  }))
})

// 个人统计
const personStatistics = computed(() => {
  const stats = {}
  badDeedsData.value.forEach((record) => {
    if (!stats[record.personName]) {
      stats[record.personName] = {
        personName: record.personName,
        count: 0,
        totalScore: 0,
        categories: new Set(),
        victims: new Set(),
        severestCrime: { score: 0, name: '' }
      }
    }
    const person = stats[record.personName]
    person.count++
    person.totalScore += Math.abs(record.score)
    person.categories.add(record.karmaCategory)
    record.victims?.forEach((v) => person.victims.add(v))

    if (Math.abs(record.score) > Math.abs(person.severestCrime.score)) {
      person.severestCrime = {
        score: record.score,
        name: karmaRules.badDeeds[record.action]?.name
      }
    }
  })

  return Object.values(stats)
    .map((stat) => ({
      ...stat,
      avgScore: (stat.totalScore / stat.count).toFixed(1),
      categoriesCount: stat.categories.size,
      victimsCount: stat.victims.size,
      categories: undefined,
      victims: undefined
    }))
    .sort((a, b) => b.totalScore - a.totalScore)
})

// 表格列配置
const columns = [
  { title: '人员姓名', dataIndex: 'personName', key: 'personName', width: 100 },
  { title: '恶行类型', key: 'action', width: 120 },
  { title: '类别', key: 'category', width: 100 },
  { title: '严重程度', key: 'severity', width: 100 },
  { title: '罪孽分数', key: 'score', width: 80, align: 'center' },
  { title: '日期', dataIndex: 'date', key: 'date', width: 100 },
  { title: '地点', dataIndex: 'location', key: 'location', width: 150, ellipsis: true },
  { title: '受害者', key: 'victims', width: 80, align: 'center' },
  { title: '验证状态', key: 'verified', width: 100, align: 'center' },
  { title: '操作', key: 'actions', width: 200, fixed: 'right' }
]

// 类型统计表格列
const categoryStatsColumns = [
  { title: '恶行类型', dataIndex: 'category', key: 'category' },
  { title: '记录数量', dataIndex: 'count', key: 'count', align: 'center' },
  { title: '总罪孽分', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '平均罪孽分', dataIndex: 'avgScore', key: 'avgScore', align: 'center' },
  { title: '受害者数', dataIndex: 'victimsCount', key: 'victimsCount', align: 'center' }
]

// 严重程度统计表格列
const severityStatsColumns = [
  { title: '严重程度', dataIndex: 'level', key: 'level' },
  { title: '记录数量', dataIndex: 'count', key: 'count', align: 'center' },
  { title: '总罪孽分', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '平均罪孽分', dataIndex: 'avgScore', key: 'avgScore', align: 'center' }
]

// 个人统计表格列
const personStatsColumns = [
  { title: '人员姓名', dataIndex: 'personName', key: 'personName' },
  { title: '恶行次数', dataIndex: 'count', key: 'count', align: 'center' },
  { title: '总罪孽分', dataIndex: 'totalScore', key: 'totalScore', align: 'center' },
  { title: '平均罪孽分', dataIndex: 'avgScore', key: 'avgScore', align: 'center' },
  { title: '涉及类型', dataIndex: 'categoriesCount', key: 'categoriesCount', align: 'center' },
  { title: '受害者数', dataIndex: 'victimsCount', key: 'victimsCount', align: 'center' },
  {
    title: '最严重罪行',
    key: 'severestCrime',
    customRender: ({ record }) => record.severestCrime?.name || '无'
  }
]

// 方法
const getActionColor = (category) => {
  const colors = {
    重大犯罪: 'red',
    财产犯罪: 'orange',
    道德败坏: 'purple',
    欺凌虐待: 'magenta',
    背叛忘恩: 'volcano'
  }
  return colors[category] || 'red'
}

const getSeverityColor = (level) => {
  const colors = {
    轻微: 'orange',
    中等: 'red',
    重大: 'magenta',
    极重: 'purple'
  }
  return colors[level] || 'red'
}

const getSeverityLevel = (score) => {
  if (score >= 80) return { type: 'error', description: '后果极其严重，需要重点关注' }
  if (score >= 60) return { type: 'warning', description: '后果较为严重，需要加强监管' }
  if (score >= 40) return { type: 'info', description: '有一定后果，需要适当关注' }
  return { type: 'success', description: '后果相对较轻，正常处理即可' }
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleFilterChange = () => {
  // 过滤逻辑已在computed中处理
}

const viewRecord = (record) => {
  currentRecord.value = record
  message.info('查看详情功能')
}

const editRecord = (record) => {
  editingRecord.value = record
  Object.assign(formData, {
    ...record,
    date: record.date ? dayjs(record.date) : null,
    time: record.time ? dayjs(record.time, 'HH:mm') : null
  })
  showAddModal.value = true
}

const trackConsequences = (record) => {
  currentRecord.value = record
  // 重置追踪数据
  consequenceTracking.direct = record.consequences || ''
  consequenceTracking.indirect = ''
  consequenceTracking.economicLoss = 0
  consequenceTracking.mentalDamage = 5
  consequenceTracking.socialImpact = 5
  consequenceTracking.legalConsequence = 'none'
  consequenceTracking.followUp = ''
  showConsequenceModal.value = true
}

const deleteRecord = async (record) => {
  try {
    const result = await karmaStore.deleteKarmaRecord(record.id)
    if (result.success) {
      message.success('删除成功')
    } else {
      message.error(result.error)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

const handleSaveRecord = async () => {
  try {
    await formRef.value.validate()

    const recordData = {
      ...formData,
      type: 'badDeed',
      date: formData.date ? formData.date.format('YYYY-MM-DD') : null,
      time: formData.time ? formData.time.format('HH:mm') : null
    }

    let result
    if (editingRecord.value) {
      result = await karmaStore.updateKarmaRecord(editingRecord.value.id, recordData)
    } else {
      result = await karmaStore.addKarmaRecord(recordData)
    }

    if (result.success) {
      message.success(editingRecord.value ? '更新成功' : '添加成功')
      showAddModal.value = false
      handleCancelEdit()
    } else {
      message.error(result.error)
    }
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const handleCancelEdit = () => {
  editingRecord.value = null
  formRef.value?.resetFields()
  Object.assign(formData, {
    personName: '',
    action: '',
    description: '',
    date: null,
    time: null,
    location: '',
    witnesses: [],
    victims: [],
    consequences: '',
    evidence: [],
    status: 'pending'
  })
}

const saveConsequenceTracking = () => {
  message.success(`后果追踪已保存，综合严重度: ${consequenceTracking.totalSeverity}分`)
  showConsequenceModal.value = false
}

// 返回上级页面
const goBack = () => {
  router.push('/karma')
}

// 滚动到统计区域
const scrollToStatistics = () => {
  if (statisticsSection.value) {
    statisticsSection.value.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 图表数据计算
const categoryChartData = computed(() => {
  const stats = {}
  badDeedsData.value.forEach((record) => {
    const category = record.karmaCategory
    if (!stats[category]) {
      stats[category] = { count: 0, score: 0 }
    }
    stats[category].count++
    stats[category].score += Math.abs(record.score)
  })

  return Object.entries(stats).map(([name, data]) => ({
    name,
    value: data.count,
    score: data.score
  }))
})

const severityChartData = computed(() => {
  const stats = { 轻微: 0, 中等: 0, 重大: 0, 极重: 0 }
  badDeedsData.value.forEach((record) => {
    const rule = karmaRules.badDeeds[record.action]
    if (rule && rule.level) {
      stats[rule.level]++
    }
  })

  return Object.entries(stats).map(([name, value]) => ({ name, value }))
})

// 初始化类型分布图表
const initCategoryChart = () => {
  if (!categoryChart.value) return

  const chart = echarts.init(categoryChart.value)
  const option = {
    title: {
      text: '恶行类型分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#fff'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}次 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '恶行类型',
        type: 'pie',
        radius: '50%',
        data: categoryChartData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          color: function (params) {
            const colors = ['#ff4d4f', '#ff7875', '#ffa39e', '#ffccc7', '#ffd8d8']
            return colors[params.dataIndex % colors.length]
          }
        }
      }
    ]
  }
  chart.setOption(option)

  // 响应式调整
  window.addEventListener('resize', () => chart.resize())
}

// 初始化严重程度图表
const initSeverityChart = () => {
  if (!severityChart.value) return

  const chart = echarts.init(severityChart.value)
  const option = {
    title: {
      text: '严重程度分级',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#fff'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: severityChartData.value.map((item) => item.name)
    },
    yAxis: {
      type: 'value',
      name: '案例数量'
    },
    series: [
      {
        name: '恶行数量',
        type: 'bar',
        data: severityChartData.value.map((item) => item.value),
        itemStyle: {
          color: function (params) {
            const colors = ['#ffcc02', '#ff7f00', '#ff4500', '#8b0000']
            return colors[params.dataIndex]
          }
        }
      }
    ]
  }
  chart.setOption(option)

  // 响应式调整
  window.addEventListener('resize', () => chart.resize())
}

// 生命周期
onMounted(() => {
  karmaStore.fetchKarmaRecords()
  nextTick(() => {
    initCategoryChart()
    initSeverityChart()
  })
})

// 监听数据变化重新渲染图表
watch(
  [badDeedsData],
  () => {
    nextTick(() => {
      initCategoryChart()
      initSeverityChart()
    })
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
@use 'sass:color';

.bad-deeds-page {
  padding: 24px;
  min-height: 100vh;

  // 面包屑导航样式 - 仿照Dashboard
  .breadcrumb-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 20px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    backdrop-filter: blur(10px);

    :deep(.ant-breadcrumb) {
      .ant-breadcrumb-link {
        color: $text-secondary;

        a {
          color: $primary-color;

          &:hover {
            color: color.adjust($primary-color, $lightness: 10%);
          }
        }
      }

      .ant-breadcrumb-separator {
        color: $text-tertiary;
      }
    }

    .back-button {
      color: $primary-color;
      border: none;
      background: transparent;

      &:hover {
        color: lighten($primary-color, 10%);
        background: rgba(114, 46, 209, 0.1);
      }
    }
  }

  // 页面标题样式 - 仿照Dashboard
  .ancient-title {
    text-align: center;
    font-size: 32px;
    font-weight: bold;
    color: $secondary-color;
    margin-bottom: 48px;
    text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
    font-family: 'PingFang SC', '微软雅黑', sans-serif;
  }

  // 统计卡片区域样式
  .stats-row,
  .charts-row,
  .alert-row {
    margin-bottom: 32px;
  }

  // 统计卡片样式 - 仿照Dashboard
  .stat-card {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    padding: 24px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 3px;
      background: linear-gradient(90deg, transparent, #f5222d, transparent);
      opacity: 0.6;
    }

    :deep(.ant-statistic) {
      text-align: center;

      .ant-statistic-title {
        color: $text-secondary;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .ant-statistic-content {
        .ant-statistic-content-value {
          color: currentColor;
          font-weight: bold;
        }
      }
    }
  }

  // 图表卡片和其他卡片样式 - 仿照Dashboard section样式
  .chart-card,
  .action-card,
  .records-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    backdrop-filter: blur(10px);

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;

      .ant-card-head-title {
        color: $text-primary;
        font-size: 18px;
        font-weight: 600;
      }
    }

    :deep(.ant-card-body) {
      color: $text-primary;
    }
  }

  // 恶行记录列表特殊处理
  .records-card {
    margin-bottom: 32px;
  }

  // 统计区域样式
  .statistics-section {
    margin-top: 48px;

    .section-title {
      text-align: center;
      font-size: 24px;
      font-weight: bold;
      color: $secondary-color;
      margin-bottom: 32px;
      text-shadow: 0 0 15px rgba(212, 153, 10, 0.3);
      font-family: 'PingFang SC', '微软雅黑', sans-serif;
    }
  }

  // 统计卡片样式
  .statistics-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;

      .ant-card-head-title {
        color: $text-primary;
        font-size: 18px;
        font-weight: 600;
      }
    }

    :deep(.ant-card-body) {
      color: $text-primary;
    }
  }

  // 分数样式
  .score-negative {
    color: #f5222d;
    font-weight: bold;
  }

  // 严重犯罪列表样式
  .severe-crimes-list {
    margin-top: 8px;

    :deep(.ant-tag) {
      margin: 2px;
    }
  }

  // 警告行样式
  .alert-row {
    :deep(.ant-alert) {
      background: rgba(245, 34, 45, 0.1);
      border: 1px solid rgba(245, 34, 45, 0.2);
      border-radius: 12px;
      backdrop-filter: blur(10px);

      .ant-alert-message {
        color: #ff4d4f;
        font-weight: 600;
      }

      .ant-alert-description {
        color: $text-secondary;
      }

      .ant-alert-icon {
        color: #ff4d4f;
      }
    }
  }

  // 表格样式调整
  :deep(.ant-table) {
    background: transparent;

    .ant-table-container {
      background: transparent;
    }

    .ant-table-thead > tr > th {
      background: rgba(255, 255, 255, 0.08);
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      color: $text-primary;
    }

    .ant-table-tbody > tr > td {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      color: $text-secondary;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba(255, 255, 255, 0.05);
    }
  }

  // 标签页样式
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      &::before {
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }
    }

    .ant-tabs-tab {
      color: $text-secondary;

      &.ant-tabs-tab-active {
        color: $primary-color;
      }

      &:hover {
        color: $primary-color;
      }
    }

    .ant-tabs-ink-bar {
      background: $primary-color;
    }

    .ant-tabs-content-holder {
      .ant-tabs-content {
        color: $text-primary;
      }
    }
  }

  // 表单样式
  :deep(.ant-form) {
    .ant-form-item-label > label {
      color: $text-primary;
    }
  }

  // 输入框和选择器样式
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-input-number),
  :deep(.ant-picker),
  :deep(.ant-textarea) {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &:hover {
      border-color: $primary-color;
    }

    &:focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(114, 46, 209, 0.2);
    }
  }

  :deep(.ant-input::placeholder),
  :deep(.ant-textarea::placeholder) {
    color: $text-tertiary;
  }

  :deep(.ant-select) {
    .ant-select-selection-placeholder {
      color: $text-tertiary;
    }

    .ant-select-arrow {
      color: $text-secondary;
    }
  }

  // 单选按钮样式
  :deep(.ant-radio-group) {
    .ant-radio-wrapper {
      color: $text-primary;

      .ant-radio {
        .ant-radio-inner {
          background: rgba(255, 255, 255, 0.08);
          border-color: rgba(255, 255, 255, 0.2);
        }

        &.ant-radio-checked .ant-radio-inner {
          background: $primary-color;
          border-color: $primary-color;
        }
      }
    }
  }

  // 按钮样式调整
  :deep(.ant-btn) {
    &.ant-btn-primary {
      background: $primary-color;
      border-color: $primary-color;

      &:hover {
        background: color.adjust($primary-color, $lightness: 10%);
        border-color: color.adjust($primary-color, $lightness: 10%);
      }

      &.ant-btn-dangerous {
        background: #ff4d4f;
        border-color: #ff4d4f;

        &:hover {
          background: color.adjust(#ff4d4f, $lightness: 10%);
          border-color: color.adjust(#ff4d4f, $lightness: 10%);
        }
      }
    }

    &.ant-btn-link {
      color: $primary-color;

      &:hover {
        color: color.adjust($primary-color, $lightness: 10%);
      }

      &.ant-btn-dangerous {
        color: #ff4d4f;

        &:hover {
          color: color.adjust(#ff4d4f, $lightness: 10%);
        }
      }
    }

    &:not(.ant-btn-primary):not(.ant-btn-link) {
      background: rgba(255, 255, 255, 0.08);
      border-color: rgba(255, 255, 255, 0.2);
      color: $text-primary;

      &:hover {
        background: rgba(255, 255, 255, 0.15);
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }

  // 标签样式
  :deep(.ant-tag) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &[color] {
      border: none;
    }
  }

  // 滑块样式
  :deep(.ant-slider) {
    .ant-slider-track {
      background: $primary-color;
    }

    .ant-slider-handle {
      border-color: $primary-color;
    }

    .ant-slider-mark-text {
      color: $text-tertiary;
    }
  }

  // 警告框样式
  :deep(.ant-alert) {
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;

    .ant-alert-message {
      color: $text-primary;
    }

    .ant-alert-description {
      color: $text-secondary;
    }
  }

  // 模态框样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(30, 30, 35, 0.95);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: $text-primary;
      }
    }

    .ant-modal-body {
      color: $text-primary;
    }

    .ant-modal-footer {
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      background: transparent;
    }
  }

  // 描述列表样式
  :deep(.ant-descriptions) {
    .ant-descriptions-header {
      .ant-descriptions-title {
        color: $text-primary;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .ant-descriptions-item-label {
      color: $text-secondary;
    }

    .ant-descriptions-item-content {
      color: $text-primary;
    }
  }

  // 分割线样式
  :deep(.ant-divider) {
    border-color: rgba(255, 255, 255, 0.1);
  }

  // 时间选择器样式
  :deep(.ant-time-picker) {
    .ant-picker-input > input {
      color: $text-primary;
    }
  }

  // 日期选择器样式
  :deep(.ant-date-picker) {
    .ant-picker-input > input {
      color: $text-primary;
    }
  }

  // 空间组件样式
  :deep(.ant-space) {
    .ant-space-item {
      color: $text-primary;
    }
  }

  // 工具提示样式
  :deep(.ant-tooltip) {
    .ant-tooltip-inner {
      background: rgba(30, 30, 35, 0.95);
      color: $text-primary;
      border: 1px solid rgba(255, 255, 255, 0.15);
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .bad-deeds-page {
    .stat-card {
      height: 100px;
      padding: 20px;
    }
  }
}

@media (max-width: 768px) {
  .bad-deeds-page {
    padding: 16px;

    .stats-row,
    .charts-row,
    .alert-row {
      margin-bottom: 24px;
    }

    .stat-card {
      height: 80px;
      padding: 16px;
    }

    .breadcrumb-wrapper {
      padding: 12px 16px;
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      .back-button {
        align-self: flex-end;
      }
    }

    .records-card {
      margin-bottom: 24px;
    }

    .severe-crimes-list {
      margin-top: 4px;

      :deep(.ant-tag) {
        margin: 1px;
        font-size: 11px;
      }
    }
  }
}
</style>
